import 'dart:convert';

import 'package:f200/common/index.dart';
import 'package:get/get.dart';

class UserProfileStorage extends BaseController {
  static UserProfileStorage get to => Get.find();

  final _isLogin = false.obs;
  String _token = "";
  final _profile = UserProfileModel().obs;

  ///是否已登录
  bool get isLogin => _isLogin.value;

  ///是否有Token
  bool get hasToken => _token.isNotEmpty;

  ///用户profile
  UserProfileModel get profile => _profile.value;

  @override
  void onInit() {
    super.onInit();
    _token = StorageService.to.getString(Constants.UserTokenStorageKey);
    var profileOffline =
        StorageService.to.getString(Constants.UserProfileStorageKey);
    if (profileOffline.isNotEmpty) {
      _profile(UserProfileModel.fromJson(jsonDecode(profileOffline)));
    }
  }

  ///保存Token
  Future<void> setToken(String token) async {
    await StorageService.to.setString(Constants.UserTokenStorageKey, token);
    this._token = token;
  }

  /// 获取 profile
  Future<void> fetchProfile() async {
    if (_token.isEmpty) return;
    // var result = await UserAPI.profile();
    // _profile(result);
    // _isLogin.value = true;
    // StorageService.to.setString(STORAGE_USER_PROFILE_KEY, jsonEncode(result));
  }

  /// 保存 profile
  Future<void> saveProfile(UserProfileModel profile) async {
    _isLogin.value = true;
    StorageService.to
        .setString(Constants.UserProfileStorageKey, jsonEncode(profile));
  }

  /// 注销
  Future<void> onLogout() async {
    // if (_isLogin.value) await UserAPI.logout();
    await StorageService.to.remove(Constants.UserTokenStorageKey);
    _isLogin.value = false;
    _token = '';
  }
}
